package com.livestocksolutions.intent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.livestocksolutions.Bovine;
import com.livestocksolutions.Bull;
import com.livestocksolutions.Cow;
import com.livestocksolutions.Join;
import com.livestocksolutions.LivestockSolutions;
import com.livestocksolutions.R;
import com.livestocksolutions.ui.ListCattleArrayAdapter;
import com.livestocksolutions.ui.ViewCattleArrayAdapter;
import com.livestocksolutions.ui.ViewJoinArrayAdapter;
import com.livestocksolutions.util.StringArrayParcelable;

/* -- Version History --
 *  1.0 : 10 September 2012 - Initial version.
 */

/**
 * A class to create the layout for a Join
 * @author Adam Parr
 * @version 1.0
 * 
 * @.modified 18 October 2012
 */
public class JoinActivity extends BaseActivity {
	public static final int JOINVIEW 	 = 0;
	/**
	 * Stores the reference to the XML layout template for each view
	 * @see #JOINVIEW
	 */
	public static final Integer[] RESOURCEID = new Integer[]{
		R.layout.item,
	};
	
	/**
	 * Data related to this Joining.
	 */
	protected ViewJoinArrayAdapter joinView;
	/**
	 * List of Cows that are within this Joining.
	 */
	protected ListCattleArrayAdapter cattle;
	/**
	 * The stored ID of the bull of this Join
	 */
	private long bullID = 0;
	
	/**
	 * Constructor
	 */
	public JoinActivity() {
		super(RESOURCEID);
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if(stack.size()==0){
        	setContentView(RESOURCEID[JOINVIEW]);
        	if(!built){
	    		// Read initial state of the Join Object
    			id = id!=-1?id:getIntent().getExtras().getLong(ITEMID,-1);
    			Join j = LivestockSolutions.getJoiningByID(id);
    			
    			// Read initial state of the Join Object
	            String[] joinType = new String[ViewJoinArrayAdapter.SIZE];
	            joinType[ViewJoinArrayAdapter.ID] 			= String.valueOf(j.getID());
	            joinType[ViewJoinArrayAdapter.INSERTIONDATE]= String.valueOf(j.getInsertionDate().getTime());
	            joinType[ViewJoinArrayAdapter.REMOVALDATE] 	= j.getRemovalDate()!=null?String.valueOf(j.getRemovalDate().getTime()):"";
	            joinType[ViewJoinArrayAdapter.BULL] 		= String.valueOf(bullID=j.getBull()!=null?j.getBull().getID():0);
    			
	            Cow[] cowList = j.getCows();
	            Arrays.sort(cowList, bovineComparator);
	            String[][] cowValues = new String[cowList.length][];
	            for(int x=0; x<cowList.length; x++){
	            	Date dobDate =  cowList[x].getDob();
	            	
	            	String[] item = new String[ListCattleArrayAdapter.SIZE];
	            	item[ViewCattleArrayAdapter.ID]=String.valueOf(cowList[x].getID());
	            	item[ViewCattleArrayAdapter.VISUALID]=cowList[x].getEartag().getEartagID();
	            	item[ViewCattleArrayAdapter.NLISRFID]=cowList[x].getEartag().getRfID();
	            	item[ViewCattleArrayAdapter.DOB]=dobDate!=null?String.valueOf(dobDate.getTime()):"";
	    			
	            	cowValues[x]=item;
	            }
				
    			joinView = new ViewJoinArrayAdapter(this, joinType);
    			cattle = new ListCattleArrayAdapter(this, cowValues);
		    	setPage();
		    	drawCowList();
	            
				currentState.putInt(STATEID,JOINVIEW);
				built=true;
    		}
    	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// Show the menu for an Owner Object
        getMenuInflater().inflate(R.menu.join_menu, menu);
        this.menu=menu;
        return true;
    }

    @Override
    public void onSaveInstanceState (Bundle outState) {
    	super.onSaveInstanceState (outState);
    	
    	outState.putParcelable("joinView", new StringArrayParcelable().setStrings(joinView.get()));
    	outState.putParcelable("joinCattle", new StringArrayParcelable().setStrings(cattle.get()));
    	
    	outState.putLong("bullID", bullID);
    }
    
    @Override
    public void onRestoreInstanceState(Bundle inState) {
    	joinView = new ViewJoinArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("joinView")).getStrings()[0]);
    	cattle = new ListCattleArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("joinCattle")).getStrings());
    	
    	bullID = inState.getLong("bullID");
    	
    	super.onRestoreInstanceState (inState);
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    	int position = view.getId();
    	if(position>=0 && position<cattle.getCount()){
    	}
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	return false;
    }
    
    @Override
    public boolean frameSelection(int frame) {
        switch (frame) {
        	case R.id.menu_save:
        		if(joinView.isValid()){
	        		edit = false;
	        		
	        		Join j = id==-1?new Join(new Date(Long.parseLong(joinView.get()[0][ViewJoinArrayAdapter.INSERTIONDATE])), (Bull)LivestockSolutions.getBovineByID(Long.parseLong(joinView.get()[0][ViewJoinArrayAdapter.BULL]))):LivestockSolutions.getJoiningByID(id);
	        		j.setRemovalDate(new Date(Long.parseLong(joinView.get()[0][ViewJoinArrayAdapter.REMOVALDATE])));
	        		id=j.getID();
	        		if(LivestockSolutions.addJoining(j)){
	        			Toast.makeText(this,getResources().getString(R.string.message_saved,getResources().getString(R.string.join)),Toast.LENGTH_SHORT).show();
	        		}else{
	        			Toast.makeText(this,getResources().getString(R.string.message_errorSave,getResources().getString(R.string.join),getResources().getString(R.string.message_unknown)),Toast.LENGTH_SHORT).show();
	        		}
	        		
	        		built=false;
	        		onPrepareOptionsMenu(menu);
	        		showView(currentState.getInt(STATEID,JOINVIEW),currentState);
	        		// Pop current view
	        		stack.pop();
	        		// Pop edit change
	        		stack.pop();
	        		break;
        		}
		        //$FALL-THROUGH$
			default:
	        	return super.frameSelection(frame);
        }
        return true;
    }
    
	@Override
	public boolean constructFrame(int view) {
		switch (view) {
			case JOINVIEW:
				setContentView(RESOURCEID[JOINVIEW]);
				setPage();
				drawCowList();
				break;
			default:
				return false;
		}
		return true;
	}
    
    /**
     * Set up the view to show the relevant content
     */
    protected void setPage(){
    	LinearLayout itemView = (LinearLayout) findViewById(R.id.listView);
    	// Not Implemented for a Join
    	if(edit){
		//	joinView.setModifyJoin();
	    }else{
	    //	joinView.setViewJoin();
	    }
    	joinView.setRoot(itemView);
    	
    	// Get a list of possible Bulls.
		String[] genderList=getResources().getStringArray(R.array.cattle_gender);
		Bovine[] bovines = LivestockSolutions.getBovines();
		
		ArrayList<String[]> tempBullList = new ArrayList<String[]>();
		
		String[] noParent = new String[2];
		noParent[ViewCattleArrayAdapter.ID]=String.valueOf(0);
		noParent[ViewCattleArrayAdapter.NAME]=getResources().getString(R.string.cattle_name_none);
		
		tempBullList.add(noParent);
		
		for(Bovine bovine : bovines){
			int days = bovine.getGender().equals(Bull.GENDER)?bovine.getBreed().getAverageMalePubityAgeInDays():bovine.getBreed().getAverageFemalePubityAgeInDays()-30;
			Calendar cal = Calendar.getInstance();
					cal.add(Calendar.DATE, -days);
			if(bovine.getDob()==null||bovine.getDob().before(cal.getTime())){
				String[] item = new String[2];
				item[ViewCattleArrayAdapter.ID]=String.valueOf(bovine.getID());
				item[ViewCattleArrayAdapter.NAME]=bovine.getEartag().getEartagID()+" - "+bovine.getEartag().getRfID();
				
				if(bovine.getGender().equals(genderList[ViewCattleArrayAdapter.GENDER_MALE])){	
					tempBullList.add(item);
				}
			}
		}
		joinView.setBullList(tempBullList.toArray(new String[][]{}));
    	
    	View v = joinView.getView(0,null, itemView);
    	View b = v.findViewById(R.id.joinBull);
		b.setEnabled(bullID>0);
		if(bullID>0){
    		b.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(JoinActivity.this, BovineActivity.class);
					intent.putExtra(ITEMID, bullID);
			    	startActivityForResult(intent, EXISTING);
				}
			});
		}
		itemView.addView(v,0);
    }
    
    private void drawCowList(){
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_cattle);

    	LinearLayout view = (LinearLayout) findViewById(R.id.selectiveList);
    	view.removeAllViews();
    	final ListCattleArrayAdapter listCattle = cattle;
    	if(listCattle.getCount()>0){
	    	listCattle.setRoot(view);
	    	for(int x=0; x< listCattle.getCount(); x++){
	    		View v = listCattle.getView(x, null, view);
	    		v.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(JoinActivity.this, BovineActivity.class);
						intent.putExtra(ITEMID, Long.parseLong(cattle.getItem(v.getId())[ViewJoinArrayAdapter.ID]));
				    	startActivityForResult(intent, EXISTING);
					}
				});
	    		
	    		view.addView(v,x);
	    	}
	    }else{
			view.addView(inflateLayout(R.layout.item_none,view));
		}
    }
}
